package com.lushixiang.service.user.impl;

import com.lushixiang.database.UserDao;
import com.lushixiang.mybatis.entity.user.UserEntity;
import com.lushixiang.mybatis.entity.usercheckcode.UserCheckCodeEntity;
import com.lushixiang.service.mail.MailService;
import com.lushixiang.service.userCheckCode.UserCheckCodeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.lushixiang.service.user.UserService;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;

import static com.lushixiang.StaticVariables.checkCodeLastTime;

@Slf4j
@Component
public class UserServiceImpl implements UserService {

    @Autowired
    UserDao user;

    @Autowired
    UserCheckCodeService userCheckCodeService;

    @Autowired
    MailService mailService;

    public boolean userSignIn(String emailAddr, String password){
        log.info("用户登录信息：{},密码：{}",emailAddr,password);
        if(emailAddr==null || password==null){
            return false;
        }else {
            UserEntity userEntity = user.selectUserByEmailAddr(emailAddr);
            return password.equals(userEntity.getPassword());
        }
    }

    @Override
    public boolean changePaswdByEmailAdd(String emailAddr, String password) {
        return user.updateUserPasswordByEmailAddr(emailAddr, password);
    }

    @Override
    public List<UserEntity> selectAllUser() {
        try{
            return user.selectAllUser();
        }catch (Exception e){
            return null;
        }
    }

    @Override
    public UserEntity queryUserInfo(String emailAddr) {
        return user.selectUserByEmailAddr(emailAddr);
    }

    @Override
    public boolean modifyUserIcon(MultipartFile file, String emailAddr) {
        File dest = new File("/app/sip/user/" + emailAddr+".jpg");
        try{
            file.transferTo(dest);
            UserEntity userEntity = new UserEntity();
            userEntity.setEmailAddr(emailAddr);
            userEntity.setIconPath("/static/" + emailAddr+".jpg");
            if(user.updateUserSelectiveByEmailAddr(userEntity)){
                log.info("用户{}自定义icon成功",emailAddr);
                return true;
            }
            log.info("用户{}自定义icon失败",emailAddr);
            return false;
        }catch (IOException e){
            log.error("保存文件过程出现问题：{}", e.toString());
           return false;
        }
    }


    @Override
    public boolean isEmailRegisted(String emailAddr) {
        if(user.selectUserByEmailAddr(emailAddr)!=null){
            log.info("邮箱{}已存在无法重复注册",emailAddr);
            return true;
        }
        log.info("邮箱{}可注册",emailAddr);
        return false;
    }


    @Override
    public boolean userRegist(String userName, String password, String checkCode, String emailAddr, String status) {
        UserEntity userEntity = new UserEntity();
        userEntity.setEmailAddr(emailAddr);
        userEntity.setUserName(userName);
        userEntity.setPassword(password);
        userEntity.setStatus(status);
        if(!user.inserToUser(userEntity)){
            log.error("{} 插入用户表失败，无法完成注册",userEntity);
            return false;
        }
        log.info("{}插入用户表成功，完成注册",userEntity);
        return true;
    }

    @Override
    public boolean userDeregist(String emailAddr) {
        return user.userDeregist(emailAddr);
    }

//    @Override
//    public boolean needCheckEmail(String emailAddr) {
//        UserEntity userEntity = user.selectUserByEmailAddr(emailAddr);
//        if(userEntity!=null && "000".equals(userEntity.getStatus()) ){
//            log.info("用户{}存在并需要验证邮箱{}",userEntity,emailAddr);
//            return true;
//        }
//        log.info("用户{}不需要验证邮箱{}",userEntity,emailAddr);
//        return false;
//    }

    @Override
    public boolean applyCheckEmailAddr(String emailAddr, String code) {
        UserCheckCodeEntity userCheckCodeEntity  = userCheckCodeService.selectByEmailAddr(emailAddr);
        if(userCheckCodeEntity == null){
            log.info("邮件{}查询结果为null",emailAddr);
            return false;
        }

        Date startTime = userCheckCodeEntity.getStartTime();
        if(new Date().getTime()>startTime.getTime()+checkCodeLastTime){
            log.info("{}的验证码：{}已过期",emailAddr,userCheckCodeEntity.getCheckCode());
            return false;

        }
        if(code.equals(userCheckCodeEntity.getCheckCode())){
            try{
                user.updateUserStatusByEmailAddr(emailAddr);
            }catch (Exception e){
                log.info("邮件{}系统验证码{}，用户提交验证码{}验证成功，但更新user表用户状态失败",emailAddr,userCheckCodeEntity.getCheckCode(),code);
                return false;
            }
            log.info("邮箱{}验证成功，系统验证码{}，用户提交验证码{}验证成功",emailAddr,userCheckCodeEntity.getCheckCode(),code);
            return true;
        }
        log.info("邮箱{}验证失败，系统验证码{}，用户提交验证码{}验证失败",emailAddr,userCheckCodeEntity.getCheckCode(),code);
        return false;
    }

    @Override
    public boolean applyEmailAddrCheck(String emailAddr) {
        // 尝试删除上一条数据

        String subject = " 验证邮件";
        String code = String.valueOf((int) Math.round((Math.random()) * 10000));
        UserCheckCodeEntity userCheckCodeEntity = new UserCheckCodeEntity();
        userCheckCodeEntity.setCheckCode(code);
        userCheckCodeEntity.setEmailAddr(emailAddr);
        try{
            mailService.sendMail(emailAddr,subject,code);
        }catch (Exception e){
            log.error("邮件发送失败 {}", e.toString());
            return false;
        }
        try{
            userCheckCodeEntity.setStartTime(new Date());
            userCheckCodeService.insert(emailAddr,code);
        }catch (Exception e){
            log.error("邮件{}更新验证码表失败{}",emailAddr,e);
            return false;
        }
        log.info("邮件发送{}成功,更新验证码表成功，验证码是{}",emailAddr,code);
        return true;
    }
}
